package com.mall.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.result.Result;
import com.mall.system.entity.UserEntity;
import com.mall.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 */
@Tag(name = "用户接口")
@Slf4j
@RestController
@RequestMapping("/system/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Operation(summary = "用户列表")
    @GetMapping
    public Result<IPage<UserEntity>> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            UserEntity user) {
        try {
            IPage<UserEntity> page = new Page<>(pageNum, pageSize);
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            
            // 添加查询条件
            if (user.getUsername() != null && !user.getUsername().isEmpty()) {
                queryWrapper.like("username", user.getUsername());
            }
            if (user.getNickname() != null && !user.getNickname().isEmpty()) {
                queryWrapper.like("nickname", user.getNickname());
            }
            if (user.getMobile() != null && !user.getMobile().isEmpty()) {
                queryWrapper.like("mobile", user.getMobile());
            }
            if (user.getEmail() != null && !user.getEmail().isEmpty()) {
                queryWrapper.like("email", user.getEmail());
            }
            
            IPage<UserEntity> result = userService.page(page, queryWrapper);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询用户列表异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据用户名获取用户")
    @GetMapping("/{username}")
    public Result<UserEntity> getByUsername(@PathVariable("username") String username) {
        try {
            UserEntity user = userService.getByUsername(username);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.failed("用户不存在");
            }
        } catch (Exception e) {
            log.error("查询用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据手机号获取用户")
    @GetMapping("/mobile/{mobile}")
    public Result<UserEntity> getByMobile(@PathVariable("mobile") String mobile) {
        try {
            UserEntity user = userService.getByMobile(mobile);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.failed("用户不存在");
            }
        } catch (Exception e) {
            log.error("查询用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据邮箱获取用户")
    @GetMapping("/email/{email}")
    public Result<UserEntity> getByEmail(@PathVariable("email") String email) {
        try {
            UserEntity user = userService.getByEmail(email);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.failed("用户不存在");
            }
        } catch (Exception e) {
            log.error("查询用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据第三方平台唯一ID获取用户")
    @GetMapping("/thirdParty/{thirdPartyId}")
    public Result<UserEntity> getByThirdPartyId(@PathVariable("thirdPartyId") String thirdPartyId) {
        try {
            UserEntity user = userService.getByThirdPartyId(thirdPartyId);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.failed("用户不存在");
            }
        } catch (Exception e) {
            log.error("查询用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据用户ID获取用户")
    @GetMapping("/id/{userId}")
    public Result<UserEntity> getById(@PathVariable("userId") Long userId) {
        try {
            UserEntity user = userService.getById(userId);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.failed("用户不存在");
            }
        } catch (Exception e) {
            log.error("查询用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "新增用户")
    @PostMapping
    public Result<UserEntity> add(@RequestBody UserEntity user) {
        try {
            boolean success = userService.save(user);
            if (success) {
                return Result.success(user);
            } else {
                return Result.failed("新增用户失败");
            }
        } catch (Exception e) {
            log.error("新增用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "创建用户（用于第三方登录）")
    @PostMapping("/create")
    public Result<UserEntity> createUser(@RequestBody UserEntity user) {
        try {
            UserEntity createdUser = userService.create(user);
            return Result.success(createdUser);
        } catch (Exception e) {
            log.error("创建用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "更新用户")
    @PutMapping
    public Result<Boolean> update(@RequestBody UserEntity user) {
        try {
            boolean success = userService.updateById(user);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("更新用户失败");
            }
        } catch (Exception e) {
            log.error("更新用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "删除用户")
    @DeleteMapping("/{ids}")
    public Result<Boolean> delete(@PathVariable("ids") List<Long> ids) {
        try {
            boolean success = userService.removeByIds(ids);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("删除用户失败");
            }
        } catch (Exception e) {
            log.error("删除用户异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody UserEntity user) {
        try {
            boolean success = userService.register(user);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("注册失败");
            }
        } catch (Exception e) {
            log.error("用户注册异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "绑定第三方账号")
    @PutMapping("/bind-third-party")
    public Result<Boolean> bindThirdParty(@RequestBody UserEntity user) {
        try {
            // 只更新第三方账号信息
            UserEntity updateUser = new UserEntity();
            updateUser.setUserId(user.getUserId());
            updateUser.setThirdPartyId(user.getThirdPartyId());
            updateUser.setUpdateTime(java.time.LocalDateTime.now());
            
            boolean success = userService.updateById(updateUser);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("绑定第三方账号失败");
            }
        } catch (Exception e) {
            log.error("绑定第三方账号异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
}